import os,sys,math
import pygame
from pygame.locals import *

from command import *

def load_image(file):
    "loads an image, prepares it for play"
    #file = os.path.join('data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error())
    return surface.convert()

def load_images(*files):
    imgs = []
    for file in files:
        imgs.append(load_image(file))
    return imgs


class dummysound:
    def play(self): pass

def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join('data', file)
    try:
        sound = pygame.mixer.Sound(file)
        return sound
    except pygame.error:
        print 'Warning, unable to load,', file
    return dummysound()


class GameObject(pygame.sprite.Sprite):
    images = None 
    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.containers)
        if self.__class__.images is None:
            self.loadFiles()
    def loadFiles(self):
        pass
    def keyDownEvent(self,event):
        pass
    def getScreenRect(self):
        return self.game.getScreenRect()

class Player(GameObject):
    def __init__(self):
        GameObject.__init__(self)
        i = self.image = self.images[0]
        self.rect = i.get_rect(center=self.getScreenRect().center)
        self.moveVec = [1,0]
        self.angle = 0
        self.velocity = 0
        #self.rect = i.get_rect(midbottom=self.getScreenRect().midbottom)
    def getDirection(self):
        ox,oy = 1,0
        a = self.angle
        x = ox*math.cos(a)+oy*math.sin(a)
        y = oy*math.cos(a)-ox*math.sin(a)
        return x,y
    def rotateShip(self,direction,amount=5):
        self.angle += amount*direction
        x,y = self.rect.center
        self.image = pygame.transform.rotate(Player.images[0],self.angle)
        self.rect = self.image.get_rect(center=(x,y))
    def impulse(self,direction):
        self.velocity += direction
    def keyDownEvent(self,event):
        if event.key == K_w:
            self.impulse(1)
        elif event.key == K_a:
            self.rotateShip(1)
        elif event.key == K_d:
            self.rotateShip(-1)
        elif event.key == K_s:
            self.impulse(-1)
    def loadFiles(self):
        if 0:
            placeholder = pygame.Surface((20,20))
            placeholder.fill((255,0,0))
            Player.images = [placeholder]
        else:
            fighterImage = load_image('redfighter.gif')
            Player.images = []
            dx = 30
            for i in range(6):
                rect = (i*dx,0,dx,40)
                #print rect,fighterImage
                surf = fighterImage.subsurface(rect)
                Player.images.append(surf)
            rect = (180,0,29,40)
            surf = fighterImage.subsurface(rect)
            Player.images.append(surf)
    def update(self):
        #self.image = Player.images[self.game.frameNumber%len(Player.images)]
        x,y = self.rect.center
        dx,dy = self.moveVec[0]*self.velocity,self.moveVec[1]*self.velocity
        self.rect.center = x+dx,y+dy
        #print self.rect.center
        pass
        
class Map(GameObject):
    def __init__(self,whichMap=0):
        GameObject.__init__(self)
        self.whichMap = whichMap
        self.setupMap()
        
        self.rect = self.image.get_rect(center=self.getScreenRect().center)

    def setupMap(self):
        self.image = self.images[self.whichMap]
    def loadFiles(self):
        Map.images = [load_image('space5.jpg')]

    def getPlayerStart(self):
        pass
    def update(self):
        pass
        
class Game:
    screenRect = Rect(0, 0, 800, 600)
    windowStyle = 0  #|FULLSCREEN
    def __init__(self,windowStyle=windowStyle,):
        self.score = 0
        self.frameNumber = 0
        self.windowStyle = windowStyle
    def getScreenRect(self):
        return self.screenRect
    def play(self):
        # Initialize pygame
        pygame.init()
        if pygame.mixer and not pygame.mixer.get_init():
            print 'Warning, no sound'
            pygame.mixer = None
        self.bestDepth = pygame.display.mode_ok(
            Game.screenRect.size,
            self.windowStyle,
            32,
            )
        screen = pygame.display.set_mode(
            Game.screenRect.size,
            self.windowStyle,
            self.bestDepth,
            )

        all = pygame.sprite.RenderUpdates()
        #all = pygame.sprite.OrderedUpdates()

        Map.game = self
        Map.containers = all

        Player.game = self
        Player.containers = all

        #create the background, tile the bgd image
        bgdtile = load_image('space5.jpg')
        background = pygame.Surface(Game.screenRect.size)
        for x in range(0, Game.screenRect.width, bgdtile.get_width()):
            background.blit(bgdtile, (x, 0))
        screen.blit(background, (0,0))
        pygame.display.flip()
        #currentMap = self.currentMap = Map()
        player = self.player = Player()

        clock = pygame.time.Clock()
        while 1:
            #get input
            self.frameNumber += 1
            for event in pygame.event.get():
                if event.type == QUIT or \
                    (event.type == KEYDOWN and event.key == K_ESCAPE):
                        return
                elif event.type == KEYDOWN:
                    player.keyDownEvent(event)
                
            #draw the map
            #screen.blit(currentMap.image,currentMap.rect)
            # clear/erase the last drawn sprites
            all.clear(screen, background)

            #update all the sprites
            all.update()

            #draw the objects
            dirty = all.draw(screen)
            print dirty
            pygame.display.update(dirty)

            pygame.display.flip()
            #cap the framerate
            clock.tick(20)

        if pygame.mixer:
            pygame.mixer.music.fadeout(1000)
        pygame.time.wait(1000)

if __name__=='__main__':
    game = Game()
    game.play()
        
